package com.zetatech.bdp.parser.processor.impl;

import com.zetatech.bdp.entity.Field;
import com.zetatech.bdp.parser.processor.LineProcessor;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author cheng.cao@zetatech.com.cn
 */
public class SimpleLineProcessor implements LineProcessor<Map<String, String>> {

    @Override
    public Map<String, String> processLine(File file, String line, List<Field> fields) throws IOException {
        System.out.println(line);
        String[] items = line.split(" +", fields.size());
        Map<String, String> result = new HashMap<>();
        for (Field ff : fields) {
            int index = Integer.valueOf(ff.getProperty());
            String column = ff.getColumn();
            String staticValue = ff.getValue();
            if (index < 0) {
                if (staticValue.contains("${file_name}")) {
                    staticValue = staticValue.replace("${file_name}#", "");
                    Pattern pattern = Pattern.compile(staticValue);
                    Matcher m = pattern.matcher(file.getAbsolutePath());
                    if (m.find()) {
                        result.put(column, m.group());
                    }
                } else {
                    // 认为是固定值
                    result.put(column, staticValue);
                }
            } else {
                result.put(column, items[index]);
            }
        }
        return result;
    }

}
